package com.elder.business.service.impl;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.ElderMedicatePaln;
import com.elder.business.domain.ElderlyApartmentBeds;
import com.elder.business.domain.ElderlyInfo;
import com.elder.business.domain.MemberInfo;
import com.elder.business.mapper.ApartmentRoomInfoMapper;
import com.elder.business.mapper.ElderMedicatePalnMapper;
import com.elder.business.mapper.ElderlyInfoMapper;
import com.elder.business.mapper.MemberInfoMapper;
import com.elder.business.service.IElderMedicatePalnService;
import com.elder.common.core.domain.AjaxResult;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用药计划Service业务层处理
 * 
 * @author elder
 * @date 2024-04-20
 */
@Service
public class ElderMedicatePalnServiceImpl implements IElderMedicatePalnService
{
    @Autowired
    private ElderMedicatePalnMapper elderMedicatePalnMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private ApartmentRoomInfoMapper roomInfoMapper;
    /**
     * 查询用药计划
     * 
     * @param id 用药计划主键
     * @return 用药计划
     */
    @Override
    public JSONObject selectElderMedicatePalnById(Long id)
    {
        ElderMedicatePaln v = elderMedicatePalnMapper.selectElderMedicatePalnById(id);
        ElderlyInfo elder = Objects.isNull(v.getElderId())?new ElderlyInfo(): elderlyInfoMapper.getElderInfoByElderId(v.getElderId());
        JSONObject obj = new JSONObject();
        obj.put("id", StringNewUtils.formatStr(v.getId()));
        obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
        obj.put("elderName", elder.getElderName());
        obj.put("drugName", v.getDrugName());
        obj.put("morning", v.getMorning());
        obj.put("morningFinish", v.getMorningFinish()==0?"待完成":"完成");
        obj.put("noon", v.getNoon());
        obj.put("noonFinish", v.getNoonFinish()==0?"待完成":"完成");
        obj.put("afterNoon", v.getAfterNoon());
        obj.put("afterNoonFinish", v.getAfterNoonFinish()==0?"待完成":"完成");
        obj.put("takeTime", DateUtils.dateStr(v.getTakeTime()));
        return obj;
    }

    /**
     * 查询用药计划列表
     * 
     * @param elderMedicatePaln 用药计划
     * @return 用药计划
     */
    @Override
    public List<ElderMedicatePaln> selectElderMedicatePalnList(ElderMedicatePaln elderMedicatePaln)
    {
        return elderMedicatePalnMapper.selectElderMedicatePalnList(elderMedicatePaln);
    }

    /**
     * 新增用药计划
     * 
     * @param elderMedicatePaln 用药计划
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertElderMedicatePaln(ElderMedicatePaln elderMedicatePaln)
    {
        //获取当月用药信息
        Long currentMonthStartTime = DateUtils.getCurrentMonthStartTime();
        Long currentMonthEndTime = DateUtils.getCurrentMonthEndTime();
        ElderMedicatePaln medicatePaln = elderMedicatePalnMapper.getElderMedicatePalnCurrentMonth(currentMonthStartTime, currentMonthEndTime,1);
        if(Objects.nonNull(medicatePaln)){
            return new AjaxResult(200,"201");
        }
        Long pId = SnowGenerator.getId();
        elderMedicatePaln.setId(pId);
        Long time = DateUtils.getLongTime();
        elderMedicatePaln.setCreateTime(time);
        elderMedicatePaln.setTakeTime(DateUtils.getMonthLongTime(elderMedicatePaln.getMedicateTime()));
        elderMedicatePaln.setPlanType(1);
        //初始化记录
        CompletableFuture.runAsync(()->{
            List<Long> monthDaysList = DateUtils.getMonthDaysList();
            Long elderId = elderMedicatePaln.getElderId();
            ElderMedicatePaln plan = new ElderMedicatePaln();
            for(Long day : monthDaysList){
                plan = new ElderMedicatePaln();
                plan.setId(SnowGenerator.getId());
                plan.setElderId(elderId);
                plan.setCreateTime(time);
                plan.setTakeTime(day);
                plan.setPlanType(2);
                plan.setMorning(elderMedicatePaln.getMorning());
                plan.setNoon(elderMedicatePaln.getNoon());
                plan.setAfterNoon(elderMedicatePaln.getAfterNoon());
                plan.setPId(pId);
                elderMedicatePalnMapper.insertElderMedicatePaln(plan);
            }
        });
        elderMedicatePalnMapper.insertElderMedicatePaln(elderMedicatePaln);
        return new AjaxResult(200,"200");
    }

    /**
     * 修改用药计划
     * 
     * @param elderMedicatePaln 用药计划
     * @return 结果
     */
    @Override
    public int updateElderMedicatePaln(ElderMedicatePaln elderMedicatePaln)
    {
        elderMedicatePaln.setTakeTime(DateUtils.getTargetDateSeconds(elderMedicatePaln.getMedicateTime()));
        return elderMedicatePalnMapper.updateElderMedicatePaln(elderMedicatePaln);
    }

    /**
     * 批量删除用药计划
     * 
     * @param ids 需要删除的用药计划主键
     * @return 结果
     */
    @Override
    public int deleteElderMedicatePalnByIds(Long[] ids)
    {

        int i = elderMedicatePalnMapper.deleteElderMedicatePalnByIds(ids);
        return elderMedicatePalnMapper.deleteElderMedicatePalnByIds(ids);
    }

    /**
     * 删除用药计划信息
     * 
     * @param id 用药计划主键
     * @return 结果
     */
    @Override
    public int deleteElderMedicatePalnById(Long id)
    {
        List<ElderMedicatePaln> elderMedicatePalnPIdList = elderMedicatePalnMapper.getElderMedicatePalnPIdList(id);
        List<Long> list = elderMedicatePalnPIdList.stream().map(ElderMedicatePaln::getId).collect(Collectors.toList());
        list.add(id);
        return elderMedicatePalnMapper.deleteElderMedicatePalnByPlanIds(list);
    }

    @Override
    public TableDataInfo getElderMedicatePalnList(Long userId,Long elderId,Integer planType, Integer pageNum, Integer pageSize) {
        if(Objects.isNull(userId)){
            return new TableDataInfo();
        }
//        MemberInfo member = memberInfoMapper.getMember(userId);
        //获取房间中的elderid
//        List<ElderlyApartmentBeds> bedInfoList = roomInfoMapper.getRoomBedInfoByNurseId(member.getMemberId());
//        List<Long> elderIds = bedInfoList.stream().filter(rel -> Objects.nonNull(rel.getElderId())).map(ElderlyApartmentBeds::getElderId).collect(Collectors.toList());

        if(Objects.isNull(elderId)){
            return new TableDataInfo().getResult(new ArrayList<>(),0L);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ElderMedicatePaln> list = elderMedicatePalnMapper.getElderMedicatePalnListByElderId(elderId,planType);
        PageInfo<ElderMedicatePaln> pageInfo = new PageInfo<>(list);
        List<ElderMedicatePaln> elderList = pageInfo.getList();

        if(CollectionUtils.isEmpty(elderList)){
            return new TableDataInfo().getResult(new ArrayList<>(),0L);
        }
        List<Long> elderIdLists = elderList.stream().map(ElderMedicatePaln::getElderId).collect(Collectors.toList());
        Map<Long,String> elderMap = CollectionUtils.isEmpty(elderIdLists)?new HashMap<>():
                elderlyInfoMapper.getElderInfoByElderIds(elderIdLists).stream().collect(Collectors.toMap(ElderlyInfo::getElderId,ElderlyInfo::getElderName));
        List<JSONObject> returnList = elderList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("id", StringNewUtils.formatStr(v.getId()));
            obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
            obj.put("elderName", elderMap.get(v.getElderId()));
            obj.put("drugName", v.getDrugName());
            obj.put("morning", v.getMorning());
            obj.put("morningFinish", v.getMorningFinish());
            obj.put("noon", v.getNoon());
            obj.put("noonFinish", v.getNoonFinish());
            obj.put("afterNoon", v.getAfterNoon());
            obj.put("afterNoonFinish", v.getAfterNoonFinish());
            obj.put("takeTime", DateUtils.dateStr(v.getTakeTime()));
            obj.put("medicateTime",DateUtils.dateYearMonth(v.getTakeTime()));
            return obj;
        }).collect(Collectors.toList());

        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("success");
        dataInfo.setTotal(pageInfo.getTotal());
        dataInfo.setRows(returnList);
        return dataInfo;
    }
}
